package com.zeei.bfs.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.zeei.bfs.dao.DeptinfoDao;
import com.zeei.bfs.dao.UserDao;
import com.zeei.bfs.dao.UserRoleDao;
import com.zeei.bfs.service.UserService;
import com.zeei.bfs.vo.DeptinfoVO;
import com.zeei.bfs.vo.QueryUserParamVO;
import com.zeei.bfs.vo.UserRoleVO;
import com.zeei.common.constant.GlobalConstant;
import com.zeei.common.algorithm.CryptographyUtil;
import com.zeei.common.utils.SessionInfoUtil;
import com.zeei.common.utils.TreeUtil;
import com.zeei.common.vo.TreeNodeVO;
import com.zeei.common.vo.UserVO;

@Service("userService")
public class UserServiceImpl extends BasicServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;

	@Autowired
	private UserRoleDao userRoleDao;
	
	@Autowired
	private DeptinfoDao deptinfoDao;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public PageInfo<UserVO> queryUser(QueryUserParamVO queryUserParam, UserVO userInfo) {
		Map condition = queryUserParam.convertConditionMap();
		condition.put("adminName", GlobalConstant.ADMIN_NAME);
		condition.put("searchusername", queryUserParam.getSearchUserName());

		if (!GlobalConstant.ADMIN_NAME.equalsIgnoreCase(userInfo.getLoginname())) {
			List<String> deptIdList = getDeptIdList();
//			condition.put("deptId", userInfo.getDeptid());
			condition.put("deptIdList", deptIdList);
			// condition.put("selfId", userInfo.getUserid());//用户登录可以看到自己的用户
		}
		this.setPage(queryUserParam.getPage(), queryUserParam.getRows());
		List<UserVO> list = userDao.queryUserByCondition(condition);
		return new PageInfo<>(list);
	}
	
	private List<String> getDeptIdList() {
		UserVO user = SessionInfoUtil.getSessionUserInfo();
		String deptId = null;
		if (!GlobalConstant.ADMIN_NAME.equalsIgnoreCase(user.getLoginname())) {
			Integer id = user.getDeptid();
			deptId = id.toString();
			List<DeptinfoVO> list = deptinfoDao.queryDeptinfoByCondition(new HashMap<String,Object>());
			List<String> deptIds = getTreeNodeIds(list,deptId);
			return deptIds;
		}
		return new ArrayList<String>();
	}
	
	private List<String> getTreeNodeIds(List<DeptinfoVO> list, String deptId) {
		List<TreeNodeVO<DeptinfoVO>> treeList = TreeUtil.buildTreeNodeTree(list, deptId);
		List<String> deptIds=new ArrayList<String>();
		getTreeNodes(treeList,deptIds);
		return deptIds;
	}
	
	private void getTreeNodes(List<TreeNodeVO<DeptinfoVO>> treeList,List<String> deptIds){
		for(TreeNodeVO<DeptinfoVO> node:treeList){
			if(StringUtils.isNotEmpty(node.getId())){
				deptIds.add(node.getId());
			}
			if(CollectionUtils.isNotEmpty(node.getChildren())){
				getTreeNodes(node.getChildren(),deptIds);
			}
		}
	}

	@Override
	public Integer addUser(UserVO user) {
		// 1)修改用户信息
		user.setLoginpw(DigestUtils.md5Hex(user.getLoginpw()));
		userDao.insertUser(user);
		// 2)修改用户角色信息
		String roleIds = user.getRoleIds();
		if (StringUtils.isNotEmpty(roleIds)) {
			String[] roleIdArray = roleIds.split(",");
			for (String roleId : roleIdArray) {
				UserRoleVO vo = new UserRoleVO();
				vo.setRoleId(Integer.parseInt(roleId));
				vo.setUserId(user.getUserid());
				userRoleDao.insertUserRole(vo);
			}
		}
		return user.getUserid();
	}

	@Override
	public boolean editUser(UserVO user) {

		// 修改用户基本信息
		Integer count = userDao.updateUserNotEmptyById(user);
		// 修改用户角色信息
		userRoleDao.deleteUserRoleByUserId(user.getUserid());
		String roleIds = user.getRoleIds();
		if (StringUtils.isNotEmpty(roleIds)) {
			String[] roleIdArray = roleIds.split(",");
			for (String roleId : roleIdArray) {
				UserRoleVO vo = new UserRoleVO();
				vo.setRoleId(Integer.parseInt(roleId));
				vo.setUserId(user.getUserid());
				userRoleDao.insertUserRole(vo);
			}
		}
		return count > 0;
	}

	@Override
	public boolean dropUser(List<String> list) {
		if(CollectionUtils.isEmpty(list)){
			return true;
		}
		Integer count = userDao.deleteUserByIds(list);
		return count > 0;
	}

	@Override
	public void updateToDefaultPassword(UserVO userVO) {
		userDao.updateToDefaultPassword(userVO);
	}

	@Override
	public boolean validUserLoginName(UserVO user) {
		if (user == null || StringUtils.isEmpty(user.getLoginname())) {
			return GlobalConstant.FAILED;// 失败
		}
		if (GlobalConstant.ADMIN_NAME.equalsIgnoreCase(user.getLoginname())) {
			return GlobalConstant.FAILED;// 失败
		}
		if (user.getUserid() != null) {
			UserVO queryVO = new UserVO();
			queryVO.setUserid(user.getUserid());
			List<UserVO> oldList = userDao.queryUser(queryVO);
			if (CollectionUtils.isNotEmpty(oldList) && //
					user.getLoginname().equalsIgnoreCase(oldList.get(0).getLoginname())) {
				return GlobalConstant.SUCCEED;// 成功
			}
		}
		UserVO queryVO = new UserVO();
		queryVO.setLoginname(user.getLoginname());
		List<UserVO> userList = userDao.queryUser(queryVO);
		if (CollectionUtils.isNotEmpty(userList)) {
			return GlobalConstant.FAILED;// 失败
		}
		return GlobalConstant.SUCCEED;// 成功
	}

	@Override
	public UserVO queryUserByLoginName(UserVO userVO) {
		List<UserVO> list = userDao.queryUserByLoginName(userVO);
		if (list == null || list.isEmpty()) {
			return new UserVO();
		}
		return list.get(0);
	}

	@Override
	public UserVO getSessionUserInfoVO(String loginName) {
		UserVO userVO = new UserVO();
		userVO.setLoginname(loginName);
		List<UserVO> userList = userDao.queryUserByLoginName(userVO);
		UserVO vo = userList.get(0);
		vo.setLoginpw(null);
		return vo;
	}

	@Override
	public boolean updatePassword(UserVO userVO) {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession(false);
		if (session == null) {
			return GlobalConstant.FAILED;
		}
		UserVO userInfo = (UserVO) session.getAttribute(GlobalConstant.SESSION_USER);
		if (userInfo == null || userInfo.getLoginname() == null) {
			return GlobalConstant.FAILED;
		}
		// 验证旧密码
		UserVO queryVO = new UserVO();
		queryVO.setLoginname(userInfo.getLoginname());
		List<UserVO> userList = userDao.queryUserByLoginName(queryVO);
		if (CollectionUtils.isEmpty(userList)) {
			return GlobalConstant.FAILED;
		}
		String loginPW = CryptographyUtil.EncryptMd5Hash(userVO.getLoginpw());
		if (!userList.get(0).getLoginpw().equals(loginPW)) {
			return GlobalConstant.FAILED;
		}

		// 修改新密码
		UserVO updataVO = new UserVO();
		updataVO.setLoginname(userInfo.getLoginname());
		updataVO.setLoginpw(CryptographyUtil.EncryptMd5Hash(userVO.getNewLoginPW()));
		userDao.updateToDefaultPassword(updataVO);
		return GlobalConstant.SUCCEED;
	}

	@Override
	public List<UserVO> queryAllUser(String searchUserName, UserVO userVO) {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("adminName", GlobalConstant.ADMIN_NAME);
		condition.put("ustatus", 1);//1正常
		if (!GlobalConstant.ADMIN_NAME.equals(userVO.getLoginname())) {
			List<String> deptIdList = getDeptIdList();
			condition.put("deptIdList", deptIdList);
		}
		return userDao.queryUserByCondition(condition);
	}

	@Override
	public boolean updateSkin(UserVO userVO) {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession(false);
		if (session == null) {
			return GlobalConstant.FAILED;
		}
		UserVO userInfo = (UserVO) session.getAttribute(GlobalConstant.SESSION_USER);
		if (userInfo == null || userInfo.getLoginname() == null) {
			return GlobalConstant.FAILED;
		}
		userVO.setUserid(userInfo.getUserid());
		userDao.updateSkin(userVO);
		return GlobalConstant.SUCCEED;
	}
}
